<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>道具库存查询</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script src="/js/common.js?v=5" charset="utf-8"></script>
    <script src="/xm-select-v1.2.4/xm-select.js"></script>

    
    <style>
        .xm-select {
            width: 800px; /* 设置选择框的宽度 */
            height: auto; /* 设置选择框的高度 */
        }

        .xm-select > .xm-body {
            max-height: 400px !important; /* 设置下拉列表的最大高度 */
            overflow-y: auto !important;  /* 启用垂直滚动 */
            display: flex;  /* 使用flex布局 */
            flex-wrap: wrap; /* 允许换行 */
        }

        .xm-select > .xm-body .xm-option {
            flex: 1 1 45%; /* 每个选项占据45%的宽度 */
            height: auto; /* 设置每个选项高度为自动 */
            padding: 10px; /* 添加内边距 */
            display: flex; /* 使用flex布局 */
            align-items: center; /* 垂直居中 */
        }

        .scroll-body {
            max-height: 1000px; /* 设置高度为1000px */
            overflow-y: auto; /* 启用垂直滚动 */
            display: flex; /* 使用flex布局 */
            flex-wrap: wrap; /* 允许换行 */
        }

        .scroll-body .xm-option {
            flex: 1 1 30%; /* 每个选项占据30%的宽度，三列布局 */
            box-sizing: border-box; /* 包含内边距和边框 */
            padding: 10px; /* 添加内边距 */
        }
        
    </style>
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>道具库存查询</legend>
            <div style="margin: 10px 10px 10px 10px">
                <div class="layui-form layui-form-pane" action="javascript:;" lay-filter="table-search">
                    <div class="layui-form-item">

                        <div class="layui-inline">
                            <label class="layui-form-label">选择区服:</label>
                            <div class="layui-input-inline">
                                <select name="gameArea" class="layui-select">
                                    <option v-for="(item,index) in services" :value="item.server_id" :selected="index==0">{{item.name}}</option>
                                </select>
                            </div>
                        </div>


                        <div class="layui-inline">
                            <label class="layui-form-label">道具ID</label>
                            <div class="layui-input-inline">
                                <input type="text" name="itemId" autocomplete="off" class="layui-input" id="itemIdInput">
                            </div>
                        </div>


                        <div class="layui-inline" style="width: 600px;">
                            <label class="layui-form-label">道具名</label>
                            <div class="layui-input-inline">
                                <div id="equip"></div>
                            </div>
                        </div>
                        <br>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i>搜 索</button>
                        </div>
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- 查询结果概要 -->
        <div style="margin:10px 0;" v-if="sumCount !== null && sumCount !== undefined">
            <span style="margin-right:20px;">查询道具：{{ selectedEquipName || getEquipName(Number(selectedItemId)) }}（ID：{{ selectedItemId }}）</span>
            <span>总数量：{{ sumCount }}</span>
        </div>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="export" auth="equipment:export">导出</button>
    </div>
</script>

<script>
    var operTypes = getEnum('operType')
    var equipments = getEnum('equip')
    var serverGroup = getEnum('serverGroup')
    var equip = getEnum('equip')

    
   
    
    function getEquipName(itemId) {
        for(var k in equipments){
            if (equipments[k].id === itemId){
                return equipments[k].name;
            }
        }
        return itemId;
    }
    new Vue({
        el: "#app",
        data: {
            services: JSON.parse(localStorage.getItem('services')),
            selectedItemId: '',
            selectedEquipName: '',
            sumCount: 0,
        },
        mounted: function () {
            var _this = this;
            layui.use(['form', 'table','laydate'], function () {
                $ = layui.jquery,
                    form = layui.form,
                    table = layui.table,
                    laydate=layui.laydate;

                laydate.render({
                    elem: '#createTime0',
                    value: getYmd(0)
                });
                laydate.render({
                    elem: '#createTime1',
                    value: getYmd(1),
                })

                var data = equip.map(v => ({ name: v.name, value: v.id }));

                // 单选且与 itemId 互斥
                var xm = xmSelect.render({
                    el: '#equip',
                    name: "equip",
                    language: 'zn',
                    data: data,
                    radio: true,
                    clickClose: true,
                    filterable: true, // 启用搜索
                    toolbar: { show: true }, // 显示全选/清空工具条
                    style:{width:'800px'},
                    height: '1200px',
                    on: function(change){
                        var arr = change.arr || [];
                        if (arr.length > 0){
                            var val = arr[0].value;
                            $('#itemIdInput').val(val).prop('disabled', true);
                            _this.selectedItemId = String(val);
                            _this.selectedEquipName = arr[0].name;
                        } else {
                            $('#itemIdInput').val('').prop('disabled', false);
                            _this.selectedItemId = '';
                            _this.selectedEquipName = '';
                        }
                    }
                });

                // 输入 itemId 时禁用道具名选择
                $('#itemIdInput').on('input', function(){
                    var hasVal = $(this).val().trim().length > 0;
                    if (hasVal){
                        try{ xm.setValue([]); }catch(e){}
                        try{ xm.update({ disabled: true }); }catch(e){}
                        _this.selectedItemId = String($(this).val().trim());
                        _this.selectedEquipName = '';
                    } else {
                        try{ xm.update({ disabled: false }); }catch(e){}
                        _this.selectedItemId = '';
                        _this.selectedEquipName = '';
                    }
                });



                // 添加一个变量记录上次分页请求时间
                let lastPageTime = 0;



                function getSearchWhere(){
                    var where = form.val('table-search') || {};
                    var itemId = $('#itemIdInput').val().trim();
                    if (!itemId){
                        try{
                            var vals = (xm.getValue('value') || []);
                            if (vals.length > 0){ itemId = vals[0]; }
                        }catch(e){}
                    }
                    where.itemId = itemId;
                    if (where.equip !== undefined){ delete where.equip; }
                    return where;
                }

                table.render({
                    elem: '#currentTableId',
                    filter: 'currentTableFilter',
                    where: getSearchWhere(),
                    url: '/admin/equipment/kcpaginate',
                    defaultToolbar: ['filter', 'print' ],
                    toolbar: '#toolbarDemo',
                    width: 1850,
                    cols: [[
                        {field: 'serverId', title:'服务器ID'},
                        {field: 'memId', title:'游戏账号ID' },
                        {field: 'roleId', title:'角色ID'},
                        {field: 'nick', title:'角色名'},
                        {field: 'itemId', title:'物品ID'},
                        {field: 'equipName', title:'物品名称'},
                        {field: 'countBefore', title:'数量'},

                    ]],
                    limits: [10, 15, 20, 25, 50, 100],
                    limit: 15,
                    page: {
                        prev: '上一页',
                        next: '下一页',
                        layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
                        groups: 5
                    },
                    skin: 'line',
                    done: function(res, curr, count) {
                        console.log('表格加载完成');
                        // 记录这次请求的时间
                        lastPageTime = Date.now();


                        // 汇总信息
                        var sc = 0;
                            sc = Number(res.sumCount) || 0;
                        console.log('表格加载完成');
                        _this.$set(_this, 'sumCount', sc);
                    },
                    parseData: function(res) {
                        // 在解析返回数据之前检查时间间隔
                        let now = Date.now();
                        if (now - lastPageTime < 2000) {
                            layer.msg('请稍后再试，查询间隔需要2秒');
                            return {
                                code: 1,
                                msg: '操作太频繁',
                                count: 0,
                                data: [],
                                sumCount: 0
                            };
                        }
                        // 标准化返回，确保 sumCount 透传
                        return {
                            code: res.code || 0,
                            msg: res.msg || '',
                            count: res.count || 0,
                            data: res.data || [],
                            sumCount: typeof res.sumCount !== 'undefined' ? res.sumCount : 0
                        };
                    }
                });

                form.on('submit(data-search-btn)', function () {
                    // 执行搜索重载
                    table.reload('currentTableId', {
                        where: getSearchWhere(),
                        page: {
                            curr: 1
                        },
                        done: function (res) {
                            if (res.count >= 2999999) {
                                alert('请缩小时间范围，进行精确查询！');
                            }
                            // 重新加载后同步汇总数量
                            var sc = Number(res && res.sumCount || 0);
                            _this.$set(_this, 'sumCount', sc);
                        }
                    });

                    return false;
                });
                table.on('toolbar(currentTableFilter)', function (obj) {
                    if (obj.event === 'export') { // 导出
                        var searchData = getSearchWhere();
                        searchData.page = 1;
                        searchData.limit = 200000; // 设置较大的 limit

                        $.get('/admin/equipment/export', searchData, function (res) {
                            var totalCount = res.data.total; // 获取总条数
                            console.log('第一次返回请求数据.',totalCount);
                            var totalPages = Math.ceil(totalCount / 200000); // 计算总页数
                            var layerIndex = layer.msg("请求中请耐心等待...", { icon: 16, time: 999999999 });
                            console.log('需要分批次下载的次数.',totalPages);

                            // 存储下载文件的链接
                            var downloadLinks = [];

                            //
                            let requests = [];
                            for (let page = 1; page <= totalPages; page++) {
                                requests.push(
                                    $.get('/admin/equipment/export', { ...searchData, page: page }).then(function (data) {
                                        console.log('URL地址.',data.data.data);

                                        downloadLinks.push( data.data.data);
                                    })
                                );
                            }
                            console.log('所有请求:',requests);

                            // 等待所有请求完成
                            Promise.all(requests).then(function () {
                                layer.close(layerIndex);
                                // 处理下载链接（可以选择合并下载或逐个下载）

                                downloadLinks.forEach(function (link) {
                                    console.log('开始下载:',link);

                                    browserDownloadList(link);
                                });
                            });
                        });
                    }
                });
            });
        }
    })


</script>
</body>
</html>